package com.example.exception;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.example.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice(basePackages = "com.example.controller")
public class GlobalExceptionHandler {

    private static final Log log = LogFactory.get();


    //统一异常处理@ExceptionHandler,主要用于Exception
    @ExceptionHandler(Exception.class)
    @ResponseBody//返回json串
    public Result error(HttpServletRequest request, Exception e) {
        log.error("异常信息：", e);
        return Result.error();
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody//返回json串
    public Result customError(HttpServletRequest request, CustomException e) {
        log.error("自定义异常：{}", e.getMsg(), e);
        return Result.error(e.getMsg());
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result businessError(HttpServletRequest request, BusinessException e) {
        log.warn("业务异常：{}", e.getMsg());
        return Result.error(e.getMsg());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public Result illegalArgumentError(HttpServletRequest request, IllegalArgumentException e) {
        log.warn("参数异常：{}", e.getMessage());
        return Result.error("参数错误：" + e.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public Result nullPointerError(HttpServletRequest request, NullPointerException e) {
        log.error("空指针异常：", e);
        return Result.error("系统内部错误");
    }

}
